import Button from "@material-ui/core/Button";
import FormControl from "@material-ui/core/FormControl";
import FormHelperText from "@material-ui/core/FormHelperText";
import 'react-dropdown-tree-select/dist/styles.css'
import Input from "@material-ui/core/Input";
import DropdownTreeSelect from "react-dropdown-tree-select";
import "./index.css";
import data from "./data.json";
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormGroup from '@material-ui/core/FormGroup';
import Checkbox from '@material-ui/core/Checkbox';
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import Select from "@material-ui/core/Select";
import { makeStyles } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";
import React, { useCallback, useEffect,useMemo, useState } from "react";
import { useDispatch } from "react-redux";
import { useHistory } from "react-router";
import { toggleSnackbar } from "../../../redux/explorer";
import API from "../../../middleware/Api";
import { useTranslation } from "react-i18next";

const useStyles = makeStyles((theme) => ({
    root: {
        [theme.breakpoints.up("md")]: {
            marginLeft: 100,
        },
        marginBottom: 40,
    },
    form: {
        maxWidth: 400,
        marginTop: 20,
        marginBottom: 20,
    },
    formContainer: {
        [theme.breakpoints.up("md")]: {
            padding: "0px 24px 0 24px",
        },
    },
}));

export default function UserForm(props) {
    const { t } = useTranslation("dashboard", { keyPrefix: "user" });
    const { t: tDashboard } = useTranslation("dashboard");
    const classes = useStyles();
    const [loading, setLoading] = useState(false);
    const [user, setUser] = useState(
        props.user
            ? props.user
            : {
                  ID: 0,
                  Email: "",
                  Nick: "",
                  Password: "", // 为空时只读
                  Status: "0", // 转换类型
                  GroupID: "2", // 转换类型
                  TwoFactor: "",
                  Dirs: "",
                  Action: "",
              }
    );
    const [groups, setGroups] = useState([]);

    const history = useHistory();

    const dispatch = useDispatch();
    const ToggleSnackbar = useCallback(
        (vertical, horizontal, msg, color) =>
            dispatch(toggleSnackbar(vertical, horizontal, msg, color)),
        [dispatch]
    );

    useEffect(() => {
        API.get("/admin/groups")
            .then((response) => {
                setGroups(response.data);
            })
            .catch((error) => {
                ToggleSnackbar("top", "right", error.message, "error");
            });
    }, []);

    const handleChange = (name) => (event) => {
        setUser({
            ...user,
            [name]: event.target.value,
        });
    };

    const submit = (e) => {
        e.preventDefault();
        const userCopy = { ...user };

        // 整型转换
        ["Status", "GroupID", "Score"].forEach((v) => {
            userCopy[v] = parseInt(userCopy[v]);
        });

        setLoading(true);
        API.post("/admin/user", {
            user: userCopy,
            password: userCopy.Password,
        })
            .then(() => {
                history.push("/admin/user");
                ToggleSnackbar(
                    "top",
                    "right",
                    props.user ? t("saved") : t("added"),
                    "success"
                );
            })
            .catch((error) => {
                ToggleSnackbar("top", "right", error.message, "error");
            })
            .then(() => {
                setLoading(false);
            });
    };

    // const onChange = (currentNode, selectedNodes) => {
    //     console.log("path::", currentNode.path);
    // };
    //
    // const assignObjectPaths = (obj, stack) => {
    //     console.log(obj)
    //     Object.keys(obj).forEach(k => {
    //         const node = obj[k];
    //         if (typeof node === "object") {
    //             node.path = stack ? `${stack}.${k}` : k;
    //             assignObjectPaths(node, node.path);
    //         }
    //     });
    // };
    //
    // useEffect(() => {
    //     API.get("/admin/tree")
    //         .then((response) => {
    //             console.log(response.data,'++++++++++++++++++++++++')
    //             assignObjectPaths(response.data);
    //         })
    //         .catch((error) => {
    //             ToggleSnackbar("top", "right", error.message, "error");
    //         });
    // }, []);

    const groupSelections = useMemo(
        () =>
            groups.map((v) => {
                if (v.ID === 3) {
                    return null;
                }
                return (
                    <MenuItem key={v.ID} value={v.ID.toString()}>
                        {v.Name}
                    </MenuItem>
                );
            }),
        [groups]
    );


    return (
        <div>
            <form onSubmit={submit}>
                <div className={classes.root}>
                    <Typography variant="h6" gutterBottom>
                        {user.ID === 0 && t("new")}
                        {user.ID !== 0 && t("editUser", { nick: user.Nick })}
                    </Typography>

                    <div className={classes.formContainer}>
                        <div className={classes.form}>
                            <FormControl fullWidth>
                                <InputLabel htmlFor="component-helper">
                                    {t("email")}
                                </InputLabel>
                                <Input
                                    value={user.Email}
                                    type={"email"}
                                    onChange={handleChange("Email")}
                                    required
                                />
                            </FormControl>
                        </div>

                        <div className={classes.form}>
                            <FormControl fullWidth>
                                <InputLabel htmlFor="component-helper">
                                    {t("nick")}
                                </InputLabel>
                                <Input
                                    value={user.Nick}
                                    onChange={handleChange("Nick")}
                                    required
                                />
                            </FormControl>
                        </div>

                        <div className={classes.form}>
                            <FormControl fullWidth>
                                <InputLabel htmlFor="component-helper">
                                    {t("password")}
                                </InputLabel>
                                <Input
                                    type={"password"}
                                    value={user.Password}
                                    onChange={handleChange("Password")}
                                    required={user.ID === 0}
                                />
                                <FormHelperText id="component-helper-text">
                                    {user.ID !== 0 && t("passwordDes")}
                                </FormHelperText>
                            </FormControl>
                        </div>

                        <div className={classes.form}>
                            <FormControl fullWidth>
                                <InputLabel htmlFor="component-helper">
                                    {t("group")}
                                </InputLabel>
                                <Select
                                    value={user.GroupID}
                                    onChange={handleChange("GroupID")}
                                    required
                                >
                                    {groupSelections}
                                </Select>
                                <FormHelperText id="component-helper-text">
                                    {t("groupDes")}
                                </FormHelperText>
                            </FormControl>
                        </div>

                        <div className={classes.form}>
                            <FormControl fullWidth>
                                <InputLabel htmlFor="component-helper">
                                    {t("status")}
                                </InputLabel>
                                <Select
                                    value={user.Status}
                                    onChange={handleChange("Status")}
                                    required
                                >
                                    <MenuItem value={"0"}>
                                        {t("active")}
                                    </MenuItem>
                                    <MenuItem value={"1"}>
                                        {t("notActivated")}
                                    </MenuItem>
                                    <MenuItem value={"2"}>
                                        {t("banned")}
                                    </MenuItem>
                                    <MenuItem value={"3"}>
                                        {t("bannedBySys")}
                                    </MenuItem>
                                </Select>
                            </FormControl>
                        </div>

                        <div className={classes.form}>
                            <FormControl fullWidth>
                                <InputLabel htmlFor="component-helper">
                                    {t("2FASecret")}
                                </InputLabel>
                                <Input
                                    value={user.TwoFactor}
                                    onChange={handleChange("TwoFactor")}
                                />
                            </FormControl>
                            <FormHelperText id="component-helper-text">
                                {t("2FASecretDes")}
                            </FormHelperText>
                        </div>
                        <div style={{marginTop: 35}}>
                            <InputLabel fullWidth>
                                {t("userAuthority")}
                            </InputLabel>
                            <FormGroup row>
                                <FormControlLabel
                                    control={
                                        <Checkbox
                                            value="UploadFolder"
                                            color="primary"
                                        />
                                    }
                                    label="创建文件夹"
                                />
                                <FormControlLabel
                                    control={
                                        <Checkbox
                                            value="UploadFile"
                                            color="primary"
                                        />
                                    }
                                    label="上传文件"
                                />
                                <FormControlLabel
                                    control={
                                        <Checkbox
                                            value="ModifyFileName"
                                            color="primary"
                                        />
                                    }
                                    label="修改文件名"
                                />
                                <FormControlLabel
                                    control={
                                        <Checkbox
                                            value="ModifyFolderName"
                                            color="primary"
                                        />
                                    }
                                    label="修改文件夹名"
                                />
                                <FormControlLabel
                                    control={
                                        <Checkbox
                                            value="DownloadFile"
                                            color="primary"
                                        />
                                    }
                                    label="下载文件"
                                />
                                <FormControlLabel
                                    control={
                                        <Checkbox
                                            value="PackageDownload"
                                            color="primary"
                                        />
                                    }
                                    label="打包下载"
                                />
                                <FormControlLabel
                                    control={
                                        <Checkbox
                                            value="DeleteFile"
                                            color="primary"
                                        />
                                    }
                                    label="删除文件"
                                />
                                <FormControlLabel
                                    control={
                                        <Checkbox
                                            value="DeleteFolders"
                                            color="primary"
                                        />
                                    }
                                    label="删除文件夹"
                                />
                                <FormControlLabel
                                    control={
                                        <Checkbox
                                            value="BatchDeleteFile"
                                            color="primary"
                                        />
                                    }
                                    label="批量删除文件"
                                />
                                <FormControlLabel
                                    control={
                                        <Checkbox
                                            value="BatchDeleteFolders"
                                            color="primary"
                                        />
                                    }
                                    label="批量删除文件夹"
                                />
                            </FormGroup>
                        </div>
                        {/*<div style={{marginTop: 35}}>*/}
                        {/*    <InputLabel>*/}
                        {/*        {t("directoryPermission")}*/}
                        {/*    </InputLabel>*/}
                        {/*        <div>*/}
                        {/*            <DropdownTreeSelect data={data} onChange={onChange} className="mdl-demo" />*/}
                        {/*        </div>*/}
                        {/*</div>*/}
                        <FormControl fullWidth>
                                <InputLabel htmlFor="component-helper">
                                    权限目录
                                </InputLabel>
                                <Input
                                    value={user.Dirs}
                                    onChange={handleChange(
                                        "Dirs"
                                    )}
                                    multiline
                                    rowsMax="100"
                                    required
                                />
                                <FormHelperText id="component-helper-text">
                                权限目录
                                </FormHelperText>
                        </FormControl>

                            {/*<FormControl fullWidth>*/}
                            {/*    <InputLabel htmlFor="component-helper">*/}
                            {/*        操作权限*/}
                            {/*    </InputLabel>*/}
                            {/*    <Input*/}
                            {/*        value={user.Action}*/}
                            {/*        onChange={handleChange(*/}
                            {/*            "Action"*/}
                            {/*        )}*/}
                            {/*        multiline*/}
                            {/*        rowsMax="10"*/}
                            {/*        required*/}
                            {/*    />*/}
                            {/*    <FormHelperText id="component-helper-text">*/}
                            {/*    操作权限是指对目录的增C删D改U查R， 分别对应 create,delete,update,read, 多个权限逗号分开*/}
                            {/*    </FormHelperText>*/}
                            {/*</FormControl>*/}
                    </div>
                </div>
                <div className={classes.root}>
                    <Button
                        disabled={loading}
                        type={"submit"}
                        variant={"contained"}
                        color={"primary"}
                    >
                        {tDashboard("settings.save")}
                    </Button>
                </div>
            </form>
        </div>
    );
}
